package io.jee.runshan.service.impl;

import io.jee.medusa.orm.DaoSupport;
import io.jee.medusa.orm.condition.Condition;
import io.jee.medusa.orm.condition.ConditionGroup;
import io.jee.medusa.service.impl.BaseService;
import io.jee.medusa.vo.ResultBean;
import io.jee.runshan.dao.IOrderContactDao;
import io.jee.runshan.dao.IPreSaleOrderDao;
import io.jee.runshan.dao.IPreSaleOrderProductDao;
import io.jee.runshan.dao.IProductDao;
import io.jee.runshan.dao.IShoppingCarDao;
import io.jee.runshan.dao.IShoppingCarProductDao;
import io.jee.runshan.dao.IVIPDao;
import io.jee.runshan.domain.OrderContact;
import io.jee.runshan.domain.PreSaleOrder;
import io.jee.runshan.domain.PreSaleOrderProduct;
import io.jee.runshan.domain.Product;
import io.jee.runshan.domain.ShoppingCar;
import io.jee.runshan.domain.ShoppingCarProduct;
import io.jee.runshan.domain.VIP;
import io.jee.runshan.service.IPreSaleOrderService;
import io.jee.runshan.utils.DateUtils;
import io.jee.runshan.utils.JsonUtil;
import io.jee.runshan.utils.StringUtils;
import io.jee.runshan.vo.GoodsTransfer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

@Service
@Transactional
public class PreSaleOrderServiceImpl extends BaseService<PreSaleOrder> implements IPreSaleOrderService {
	private static Object synchronizedObj = new Object();
	@Resource
	private IPreSaleOrderDao preSaleOrderDao;
	@Resource
	private IShoppingCarProductDao carProductDao;
	@Resource
	private IShoppingCarDao carDao;
	@Resource
	private IVIPDao vipDao;
	@Resource
	private IPreSaleOrderDao orderDao;
	@Resource
	private IOrderContactDao contactDao;
	@Resource
	private IPreSaleOrderProductDao orderProductDao;
	@Resource
	private IProductDao productDao;
	
	
	@Override
	public ResultBean<?> doneOrder(boolean isOnce, String wxOpenid, String name, String mobile, String memo, String alipayAccount, String goods) {
		synchronized (synchronizedObj) {
			List<GoodsTransfer> list = JsonUtil.jsonToList(goods, GoodsTransfer.class);
			if (list == null || list.size() == 0) {
				return ResultBean.result(false, "内部资源请勿擅入");
			}
			
			int noStockCount = 0;
			
			List<ShoppingCarProduct> products = new ArrayList<ShoppingCarProduct>();
			for (GoodsTransfer gds : list) {
				Product product = productDao.get(gds.getId());
				ShoppingCarProduct carProduct = new ShoppingCarProduct();
				carProduct.setBuyCount(gds.getCount());
				carProduct.setBuyPrice(product.getSalesPrice());
				carProduct.setProduct(product);
				products.add(carProduct);
				
				if (gds.getCount() > product.getStock()) {
					noStockCount ++;
				}
			}
			
			if (noStockCount > 0) {
				return ResultBean.result(false, "有" + noStockCount + "件商品库存不足", products);
			}
			
			VIP vip = vipDao.unique("wxOpenid", wxOpenid);
			
			// 订单联系人
			OrderContact contact = contactDao.unique("wxOpenid", wxOpenid);
			if (contact == null) {
				contact = new OrderContact();
			}
			contact.setAlipayAccount(alipayAccount);
			contact.setMobile(mobile);
			contact.setName(name);
			contact.setVip(vip);
			contact.setMemo(memo);
			contact.setWxOpenid(wxOpenid);
			contactDao.saveOrUpdate(contact);
			
			ShoppingCar car = carDao.unique("wxOpenid", wxOpenid);
			
			// 添加订单基本信息
			PreSaleOrder order = new PreSaleOrder();
			order.setOrderCode(StringUtils.getCurrentTime() + StringUtils.getRand(5));
			order.setQRCode(order.getOrderCode());
			order.setStatus(0);
			order.setAlipayAccount(alipayAccount);
			order.setVip(vip);
			order.setContact(contact);
			order.setOrderTime(new Date());
			order.setWxOpenid(wxOpenid);
			
			int currentHour = DateUtils.getHour(new Date());
			String currentDate = DateUtils.getDate(new Date(), "yyyy-MM-dd");
			Date todayStartDate = DateUtils.parseDate(currentDate + " 09:00:00", "yyyy-MM-dd HH:mm:ss");
			Date tomorrowStartDate = DateUtils.addDay(todayStartDate, 1);
			
			if (currentHour < 9) {
				order.setCancelTimer(DateUtils.addHour(todayStartDate, 3));
			} else if (currentHour > 18) {
				order.setCancelTimer(DateUtils.addHour(tomorrowStartDate, 3));
			} else {
				order.setCancelTimer(DateUtils.addHour(new Date(), 3));
			}
			
			orderDao.save(order);

			ConditionGroup group = null;
			BigDecimal orderFullAmount = new BigDecimal(0);
			BigDecimal orderPreAmount = new BigDecimal(0);
			for (GoodsTransfer goodsTransfer : list) {
				Product product = productDao.get(goodsTransfer.getId());
				
				PreSaleOrderProduct psOrderProduct = new PreSaleOrderProduct();
				
				psOrderProduct.setBuyCount(goodsTransfer.getCount());
				psOrderProduct.setBuyPrice(product.getSalesPrice());
				psOrderProduct.setOrder(order);
				psOrderProduct.setProduct(product);
				orderProductDao.save(psOrderProduct);
				
				product.setStock(product.getStock() - goodsTransfer.getCount());
				
				if (!isOnce) {
					group = new ConditionGroup();
					group.and(Condition.onText("product.id").eq(goodsTransfer.getId()));
					group.and(Condition.onText("wxOpenid").eq(wxOpenid));
					carProductDao.delete(group);
				}
				orderFullAmount = orderFullAmount.add(product.getSalesPrice().multiply(new BigDecimal(goodsTransfer.getCount())));
				orderPreAmount = orderFullAmount.multiply(new BigDecimal(0.2));
				orderFullAmount.setScale(2, BigDecimal.ROUND_DOWN);
				orderPreAmount.setScale(2, BigDecimal.ROUND_DOWN);
			}
			
			// 完善订单价格信息
			order.setFullAmount(orderFullAmount);
			order.setPreAmount(orderPreAmount);
			orderDao.update(order);
			
			// 从新统计购物车信息
			List<ShoppingCarProduct> carProducts = carProductDao.list("wxOpenid", wxOpenid);
			car.clearProduct();
			for (ShoppingCarProduct carProduct: carProducts) {
				car.addPrudoct(carProduct);
			}
			carDao.update(car);
			return ResultBean.result(true, "订单处理成功", order);
		}
	}

	
	@Override
	public void deleteOrder(PreSaleOrder order) {
		orderProductDao.delete("order.id", order.getId());
		orderDao.delete(order);
	}

	@Override
	public void unsubscribe(PreSaleOrder order) {
		// 处理库存
		List<PreSaleOrderProduct> products = orderProductDao.list("order.id", order.getId());
		Product product ;
		for (PreSaleOrderProduct orderProduct : products) {
			product = orderProduct.getProduct();
			product.setStock(product.getStock() + orderProduct.getBuyCount());
			productDao.update(product);
		}
		
		if (order.getStatus() == 1) { // 已支付预付款
			order.setStatus(98);
		} else {
			order.setStatus(99);
		}
		orderDao.update(order);
	}
	
	@Override
	public DaoSupport<PreSaleOrder> getDao() {
		return preSaleOrderDao;
	}

}
